package cl.orangepeople.whyem.portal.backend.api.impl;

import java.math.BigDecimal;

import cl.orangepeople.whyem.portal.backend.api.ClientDataService;
import cl.orangepeople.whyem.portal.backend.api.utils.FechaUtils;
import cl.orangepeople.whyem.portal.backend.api.utils.FormatterUtils;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDDTO;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDData;
import cl.orangepeople.whyem.portal.backend.dto.client.ClientIDSearchBean;
import cl.whyem.sir.ws.ConsultaDeudorResult;
import cl.whyem.sir.ws.Deudor;
import cl.whyem.sir.ws.DeudorServices;
import cl.whyem.sir.ws.Header;
import cl.whyem.sir.ws.Rut;
import cl.whyem.sir.ws.Status;

public class ClientDataServiceImpl implements ClientDataService {
    private DeudorServices service;

    public ClientIDSearchBean getClientData(ClientIDDTO clientData) {
	ClientIDSearchBean bean = new ClientIDSearchBean();
	ClientIDData clientData2 = new ClientIDData();
	String clientID = clientData.getClientID();
	
	Rut clientRut = new Rut();
	clientRut.setNumero(clientID);
	clientRut.setDv("" + FormatterUtils.getDV(Integer.parseInt(clientID)));
	
	Header clientSearchHeader = new Header();
	clientSearchHeader.setTimestamp(FechaUtils.getActualDateTimestamp());
	clientSearchHeader.setTerminal("01");
	clientSearchHeader.setCanal("Web");
	clientSearchHeader.setEntidad("10");
	clientSearchHeader.setSecuencia(0l);
	
	ConsultaDeudorResult response = service.consultaDeudor(clientSearchHeader, clientRut);
	Status responseStatus = response.getStatus();
	
	if (responseStatus.getCodigo() == 0) {
	    Deudor deudorData = response.getDeudor();
	    Rut rut = deudorData.getRut();
	    BigDecimal newClientID = new BigDecimal(rut.getNumero());
	    clientData2.setClientID(newClientID);
	    clientData2.setClientName(deudorData.getNombres());
	    clientData2.setClientFirstSurname(deudorData.getApPaterno());
	    clientData2.setClientSecondSurname(deudorData.getApMaterno());
	    clientData2.setClientEmail(deudorData.getEmail());
	    
	    bean.setReturnCode(0);
	    bean.setClientData(clientData2);
	} else {
	    bean.setReturnCode(-1);
	    bean.setClientData(clientData2);
	}
	
	return bean;
    }

    public DeudorServices getService() {
        return service;
    }

    public void setService(DeudorServices service) {
        this.service = service;
    }
}